/*
 * HSM Proxy Project.
 * Copyright (C) 2013 FedICT.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version
 * 3.0 as published by the Free Software Foundation.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, see 
 * http://www.gnu.org/licenses/.
 */

package be.fedict.hsm.admin.webapp.jsf;

import java.lang.annotation.Annotation;
import java.util.Map;

import javax.enterprise.context.spi.Context;
import javax.enterprise.context.spi.Contextual;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;

public class ViewContext implements Context {

	@Override
	public Class<? extends Annotation> getScope() {
		return ViewScoped.class;
	}

	@Override
	public <T> T get(Contextual<T> contextual,
			CreationalContext<T> creationalContext) {
		Bean bean = (Bean) contextual;
		Map<String, Object> viewMap = getViewMap();
		if (viewMap.containsKey(bean.getName())) {
			return (T) viewMap.get(bean.getName());
		} else {
			T t = (T) bean.create(creationalContext);
			viewMap.put(bean.getName(), t);
			return t;
		}
	}

	@Override
	public <T> T get(Contextual<T> contextual) {
		Bean bean = (Bean) contextual;
		Map<String, Object> viewMap = getViewMap();
		if (viewMap.containsKey(bean.getName())) {
			return (T) viewMap.get(bean.getName());
		} else {
			return null;
		}
	}

	@Override
	public boolean isActive() {
		return true;
	}

	private Map<String, Object> getViewMap() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		UIViewRoot viewRoot = facesContext.getViewRoot();
		Map<String, Object> viewMap = viewRoot.getViewMap(true);
		return viewMap;
	}
}